import {credentials, Metadata} from "grpc"
import {PingRequest, PingReply} from "./util/status_pb"
import { StatusOpClient } from "./util/status_grpc_pb"
import {getGrpcDeadline } from "./grpcAdapter"
import GrpcTypes from "./grpcTypes";

const tryParse = (data: string): any => {
  let r
  try{
    r = JSON.parse(data)
  } catch (e) {
    console.log('err parse reponse data', e)
  }finally {
    return r
  }
}

const statusOp = new StatusOpClient('localhost:50053', credentials.createInsecure())

const req = new PingRequest()

const md = new Metadata()
const v = (+new Date()).toString()
md.add('REQ_ID', v)
console.log('reqID:', v)

let call = statusOp.ping({deadline: getGrpcDeadline(GrpcTypes.HEALTH)});


call.on('data',(res: PingReply) => {
  console.log('data=>',res.getPong());
  sendPing()
});

call.on('end',() => {
  console.log('closed from server');
});

call.on('error', (err) => {
  console.log('err from server', err);
});

function sendPing() {
  setTimeout(() => {
    console.log('very close')
    try{
      call.write(req);
    }catch (e) {
      console.log('write err', e)
    }

    console.log('very close2')
  }, 3000)
}
sendPing()